//
//  LaunchViewController.m
//  六友
//
//  Created by 裴烨烽 on 2018/12/8.
//  Copyright © 2018 币本. All rights reserved.
//

#import "LaunchViewController.h"
#import "SBJSON.h"
#import <SDWebImage/UIImageView+WebCache.h>                     // 网络图片加载

@interface LaunchViewController ()<NSURLSessionDataDelegate>
@property (nonatomic,strong)GWImageView *launchImageView;
@property (nonatomic,strong)UIView *adView;
@property (nonatomic,strong)UILabel *adLabel;
@property (nonatomic,strong)UIView *dropView;
@property (nonatomic,strong)UILabel *dropLabel;
@property (nonatomic,strong)UILabel *downLabel;
@property (nonatomic,strong)UIButton *actionButton;
@property (nonatomic,strong)UITapGestureRecognizer *tapGesture;
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic,strong)NSTimer *timer;
@property (nonatomic,assign)NSInteger timerInter;

@end

@implementation LaunchViewController

-(void)dealloc{
    NSLog(@"dismiss");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createView];
    [self interfaceManager];

}

#pragma mark - createView;
-(void)createView{
    // 1. launch Img
    self.launchImageView = [[GWImageView alloc] initWithFrame:kScreenBounds];
    self.launchImageView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.launchImageView];
    
    self.adView = [[UIView alloc]init];
    self.adView.backgroundColor = [UIColor blackColor];
    self.adView.alpha = .5f;
    [self.launchImageView addSubview:self.adView];
    
    self.adLabel = [[UILabel alloc]init];
    self.adLabel.textColor = [UIColor hexChangeFloat:@"ffffff"];
    self.adLabel.textAlignment = NSTextAlignmentCenter;
    self.adLabel.backgroundColor = [UIColor clearColor];
    self.adLabel.text = @"广告";
    self.adLabel.font = [UIFont systemFontOfSize:11.];
    CGSize adSize = [self.adLabel.text sizeWithCalcFont:self.adLabel.font constrainedToSize:CGSizeMake(CGFLOAT_MAX, 14)];
    [self.launchImageView addSubview:self.adLabel];
    
    self.adView.frame = CGRectMake(LCFloat(22), LCFloat(50), adSize.width + 2 * 5, [NSString contentofHeight:self.adLabel.font] + 2* LCFloat(3));
    self.adView.layer.cornerRadius = LCFloat(2);
    self.adView.clipsToBounds = YES;
    self.adLabel.frame = self.adView.frame;
    
    
    // dropView
    self.dropView = [[UIView alloc]init];
    self.dropView.backgroundColor = [UIColor blackColor];
    self.dropView.alpha = .5f;
    self.dropView.layer.cornerRadius = LCFloat(2);
    self.dropView.clipsToBounds = YES;
    [self.launchImageView addSubview:self.dropView];
    
    // drop
    self.dropLabel = [[UILabel alloc]init];
    self.dropLabel.textColor = [UIColor hexChangeFloat:@"ffffff"];
    self.dropLabel.font = [UIFont systemFontOfSize:11.];
    self.dropLabel.text = @"跳过";
    [self.launchImageView addSubview:self.dropLabel];
    
    self.downLabel = [[UILabel alloc]init];
    self.downLabel.backgroundColor = [UIColor clearColor];
    self.downLabel.textColor = [UIColor hexChangeFloat:@"fdb300"];
    self.downLabel.font = self.dropLabel.font;
    [self.launchImageView addSubview:self.downLabel];
    
    
    self.dropLabel.text = @"跳过";
    
    CGSize dropSize = [GWTool makeSizeWithLabel:self.dropLabel];
    CGSize downSize = [@"5" sizeWithCalcFont:self.downLabel.font constrainedToSize:CGSizeMake(CGFLOAT_MAX, 15)];
    CGFloat width = LCFloat(3)* 2 + dropSize.width + downSize.width + LCFloat(2);
    
    self.dropView.frame = CGRectMake(kScreenWidth - LCFloat(22) - width,self.adLabel.orgin_y, width, [NSString contentofHeight:self.downLabel.font] + 2 * LCFloat(2));
    
    self.dropLabel.frame = CGRectMake(self.dropView.orgin_x + LCFloat(3),self.dropView.orgin_y + LCFloat(2), dropSize.width, dropSize.height);
    self.downLabel.frame = CGRectMake(CGRectGetMaxX(self.dropLabel.frame) + LCFloat(2), self.dropLabel.orgin_y, downSize.width, downSize.height);
    
    self.actionButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.actionButton.frame = CGRectMake(self.dropView.orgin_x - LCFloat(11), self.dropView.orgin_y - LCFloat(11), self.dropView.size_width + 2 * LCFloat(11), self.dropView.size_height + 2 * LCFloat(11));
    __weak typeof(self)weakSelf = self;
    [self.actionButton buttonWithBlock:^(UIButton *button) {
        if (!weakSelf){
            return ;
        }
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf dismissAnimationManager];
    }];
    [self.view addSubview:self.actionButton];
    
    self.adView.hidden = YES;
    self.dropView.hidden = YES;
    self.downLabel.hidden = YES;
    // 4. 创建手势
    self.tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(animationStopTapManager)];
    [self.view addGestureRecognizer:self.tapGesture];
}

#pragma mark 跳转到外网
-(void)animationStopTapManager{
    [GWTool openURLWithURL:[AccountModel sharedAccountModel].rootModel.ad.href];
}

#pragma mark - 点击页面消失
-(void)dismissAnimationManager{
    UIWindow *keywindow = [[UIApplication sharedApplication] keyWindow];
    [UIView mdDeflateTransitionFromView:self.view toView:keywindow.rootViewController.view originalPoint:keywindow.center duration:3.f completion:^{
    }];
}


#pragma mark - Interface
-(void)interfaceManager{
    // URL
    NSURL *URL = [NSURL URLWithString:linkUrl];
    // 自定义session发起任务 (因为我们要在代理方法里面挑战服务器)
    __weak typeof(self)weakSelf = self;
    NSURLSessionDataTask *dataTask = [self.session dataTaskWithURL:URL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!weakSelf){
            return ;
        }
        __strong typeof(weakSelf)strongSelf = weakSelf;
        // 处理响应
        if (error == nil && data != nil) {
            // 反序列化
            NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            SBJSON *json = [[SBJSON alloc] init];
            NSDictionary *dicWithRequestJson = [json objectWithString:html error:nil];
            
            RootModel *responseModelObject = (RootModel *)[[RootModel alloc] initWithJSONDict:[dicWithRequestJson objectForKey:@"data"]];
            
            [AccountModel sharedAccountModel].rootModel = responseModelObject;
            
            strongSelf.timerInter = responseModelObject.ad.stay;
            [AccountModel sharedAccountModel].rootModel.link = responseModelObject.link;
            
            
            // 修改navbar
            dispatch_main_async_safe(^{
                NSArray *statusC = [[AccountModel sharedAccountModel].rootModel.statusbarColor componentsSeparatedByString:@"#"];
                NSString *status1 = [statusC lastObject];
                [WebViewController sharedAccountModel].statusBarView.backgroundColor = [UIColor hexChangeFloat:status1];
            });
            
            // 加载网页
            [[WebViewController sharedAccountModel] loadWeb];
            
            // slider 设置
            if ([[AccountModel sharedAccountModel].rootModel.ad.status isEqualToString:@"1"]){

                [strongSelf.launchImageView uploadImgWithNormal:responseModelObject.ad.img placehorder:nil back:^(UIImage *img) {
                    [AccountModel sharedAccountModel].adHasLoaded = YES;
                    
                    strongSelf.adView.hidden = NO;
                    strongSelf.dropView.hidden = NO;
                    strongSelf.downLabel.hidden = NO;
                    strongSelf.downLabel.text =[NSString stringWithFormat:@"%li",(long)responseModelObject.ad.stay];
                    [strongSelf startTimer];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(responseModelObject.ad.stay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [UIView animateWithDuration:responseModelObject.ad.cancel animations:^{
                            strongSelf.launchImageView.transform = CGAffineTransformMakeScale(1.1, 1.1);
                            strongSelf.launchImageView.alpha = 0;
                            strongSelf.view.alpha = 0;
                        } completion:^(BOOL finished) {
                            [strongSelf.view removeFromSuperview];
                            [[WebViewController sharedAccountModel]showUpload];
                            if ([AccountModel sharedAccountModel].hasError){
                                [[WebViewController sharedAccountModel]webFinash];
                            }
                        }];
                    });
                }];
            } else {
                strongSelf.adView.hidden = YES;
                strongSelf.dropView.hidden = YES;
                strongSelf.downLabel.hidden = YES;
                [AccountModel sharedAccountModel].adHasLoaded = YES;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(responseModelObject.ad.stay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [UIView animateWithDuration:responseModelObject.ad.cancel animations:^{
                        strongSelf.launchImageView.transform = CGAffineTransformMakeScale(1.1, 1.1);
                        strongSelf.launchImageView.alpha = 0;
                        strongSelf.view.alpha = 0;
                    } completion:^(BOOL finished) {
                        [strongSelf.view removeFromSuperview];
                        [[WebViewController sharedAccountModel]showUpload];
                        if ([AccountModel sharedAccountModel].hasError){
                            [[WebViewController sharedAccountModel]webFinash];
                        }
                    }];
                });
                
            }
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2. * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [UIView animateWithDuration:3 animations:^{
                    strongSelf.launchImageView.transform = CGAffineTransformMakeScale(1.1, 1.1);
                    strongSelf.launchImageView.alpha = 0;
                    strongSelf.view.alpha = 0;
                } completion:^(BOOL finished) {
                    
                }];
            });
        }
    }];
    // 启动任务
    [dataTask resume];
    
}

- (NSURLSession *)session {
    if (_session == nil) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    }
    return _session;
}

-(void)startTimer{
    if (self.timerInter <= 0){
        self.timerInter = [AccountModel sharedAccountModel].rootModel.ad.stay;
    }
    if (!self.timer){
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(daojishiManager) userInfo:nil repeats:YES];
    }
}

#pragma mark - 倒计时方法
-(void)daojishiManager{
    --self.timerInter;
    if (self.timerInter < 0){
        if (self.timer){
            [self.timer invalidate];
            self.timer = nil;
        }
    } else {
        self.downLabel.text = [NSString stringWithFormat:@"%li",(long)self.timerInter];
    }
}

@end
